package kr.couponplay.android.domain.message;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import kr.couponplay.android.AppContext;
import kr.couponplay.android.domain.BaseDao;
import kr.couponplay.android.domain.deal.Provider;
import kr.couponplay.android.domain.message.MessageList.Item;
import kr.couponplay.android.support.StringUtils;
import android.database.Cursor;
import android.net.Uri;

public class MessageDao extends BaseDao {
    public MessageList selectMessageList(int offset) {
    	MessageList messageList = new MessageList();
    	messageList.addAll(selectSmsList(offset));
//    	messageList.addAll(selectMmsList());
    	return messageList;
    }
    
    public List<MessageList.Item> selectSmsList(int offset) {
    	List<MessageList.Item> items = new ArrayList<MessageList.Item>();
    	Cursor cursor = getApplicationContext().getContentResolver().query(Uri.parse("content://sms/inbox"), null, makeSelection(), null, "date DESC");
    	while (cursor.moveToNext()) {
    		String address = cursor.getString(cursor.getColumnIndex("address"));
    		String message = cursor.getString(cursor.getColumnIndex("body"));
    		Date receivedDate = new Date(cursor.getLong(cursor.getColumnIndex("date")));
    		items.add(new Item(getProvider(address), address, message, receivedDate));
    	}
    	return items;
    }
    
    private Provider getProvider(String address) {
    	for (Provider provider : AppContext.getProviders(getApplicationContext())) {
    		if (StringUtils.trimToEmpty(address).equals(provider.getTelephone())) {
    			return provider;
    		}
    	}
		return null;
	}

//	private List<MessageList.Item> selectMmsList(int offset) {
//    	List<MessageList.Item> items = new ArrayList<MessageList.Item>();
//    	Cursor cursor = getApplicationContext().getContentResolver().query(Uri.parse("content://mms/inbox"), null, makeSelection(), null, "date DESC LIMIT " + offset + ", " + Constants.DEFAULT_DEAL_LIMIT_COUNT);
//    	while (cursor.moveToNext()) {
//    		String address = cursor.getString(cursor.getColumnIndex("address"));
//    		String subject = cursor.getString(cursor.getColumnIndex("sub"));
//    		Date date = new Date(cursor.getLong(cursor.getColumnIndex("date")) * 1000);
//    		items.add(new Item(getProvider(address), address, subject, date));
//    	}
//    	return items;
//    }    
    
    private String makeSelection() {
    	String result = "address IN(";
    	
    	int count = 0;
    	for (Provider provider : AppContext.getProviders(getApplicationContext())) {
    		result += "'" + provider.getTelephone() + "'";
    		if (count == AppContext.getProviders(getApplicationContext()).size() - 1) {
    			result += ")";
    		} else {
    			result += ", ";
    		}
    		count++;
    	}
    	return result;
    }
}
